import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { message } from 'antd';
import React from 'react';
import { history } from 'umi';
import styles from './index.less';
import { login } from '@/services/back/back';
import { setToken } from '@/utils/index';

const Login: React.FC = () => {
  const handleSubmit = async (values: BackApi.LoginQuery) => {
    try {
      // 登录
      const res = await login(values);
      if (res?.code !== 1000) return;
      message.success(res?.msg);
      setToken(res?.data);
      /** 此方法会跳转到 redirect 参数所在的位置 */
      if (!history) return;
      const { query } = history.location;
      const { redirect } = query as { redirect: string };
      history.push(redirect || '/');
      return;
    } catch (error) {}
  };

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          onFinish={async (values) => {
            await handleSubmit(values as BackApi.LoginQuery);
          }}
        >
          <ProFormText
            name="name"
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined className={styles.prefixIcon} />,
            }}
            rules={[
              {
                required: true,
                message: '请输入用户名!',
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined className={styles.prefixIcon} />,
            }}
            rules={[
              {
                required: true,
                message: '请输入密码！',
              },
            ]}
          />
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;
